import { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import apiClient from '../api/axios';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';
import 'katex/dist/katex.min.css'; // 引入KaTeX的CSS样式

function KnowledgePointFormPage() {
    const [title, setTitle] = useState('');
    const [content, setContent] = useState('');
    const { id } = useParams();
    const navigate = useNavigate();
    const isEditing = Boolean(id);
    const mermaidContainerRef = useRef(null);

    useEffect(() => {
        if (isEditing) {
            const fetchKnowledgePoint = async () => {
                try {
                    const response = await apiClient.get(`/knowledge-points/${id}`);
                    setTitle(response.data.title);
                    setContent(response.data.content);
                } catch (error) {
                    console.error('获取知识点失败', error);
                    alert('获取知识点失败，请查看控制台错误信息');
                }
            };
            fetchKnowledgePoint();
        }
    }, [id, isEditing]);

    const handleSubmit = async (e) => {
        e.preventDefault();
        const kpData = { title, content };
        try {
            if (isEditing) {
                await apiClient.put(`/knowledge-points/${id}`, kpData);
            } else {
                await apiClient.post('/knowledge-points', kpData);
            }
            navigate('/');
        } catch (error) {
            console.error('保存知识点失败', error);
            alert('保存知识点失败，请查看控制台错误信息');
        }
    };

    // 渲染Mermaid图表的函数
    const renderMermaid = async (markdownContent) => {
        // 检查是否有mermaid代码块
        if (!markdownContent.includes('```mermaid') || !mermaidContainerRef.current) return;

        try {
            const mermaidModule = await import('mermaid');
            const mermaid = mermaidModule.default;
            
            // 初始化mermaid
            mermaid.initialize({
                startOnLoad: false,
                theme: 'default',
                securityLevel: 'loose'
            });

            // 查找并渲染所有mermaid图表
            const mermaidBlocks = mermaidContainerRef.current.querySelectorAll('.mermaid');
            mermaidBlocks.forEach((element, index) => {
                try {
                    mermaid.render(`mermaid-${Date.now()}-${index}`, element.textContent.trim())
                        .then(({ svg, bindFunctions }) => {
                            element.innerHTML = svg;
                            if (bindFunctions) bindFunctions(element);
                        });
                } catch (err) {
                    console.error('Mermaid rendering error:', err);
                }
            });
        } catch (err) {
            console.error('Failed to load mermaid:', err);
        }
    };

    // 当内容改变时，尝试渲染mermaid图表
    useEffect(() => {
        const timer = setTimeout(() => {
            renderMermaid(content);
        }, 500); // 延迟500ms渲染，避免频繁更新

        return () => clearTimeout(timer);
    }, [content]);

    // Markdown语法提示
    const markdownTips = `
**Markdown 语法提示:**
# 一级标题
## 二级标题
**粗体** *斜体*
- 列表项
1. 有序列表项
[链接文本](http://example.com)
![图片描述](http://example.com/image.jpg)
\`行内代码\`
\`\`\`javascript
代码块
\`\`\`

**数学公式:**
行内公式: $E=mc^2$
块级公式:
$$
\\int_a^b f(x) dx = F(b) - F(a)
$$

**Mermaid图表:**
\`\`\`mermaid
graph TD;
    A[开始] --> B[处理];
    B --> C[结束];
\`\`\`
    `.trim();

    return (
        <div style={{ padding: '20px', maxWidth: '1400px', margin: '0 auto' }}>
            <div style={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center', 
                marginBottom: '1rem' 
            }}>
                <h1 style={{ margin: 0 }}>{isEditing ? '✏️ 编辑知识点' : '📝 新建知识点'}</h1>
                <button 
                    onClick={() => navigate('/')} 
                    style={{ 
                        padding: '8px 16px', 
                        backgroundColor: '#6c757d', 
                        color: 'white', 
                        border: 'none', 
                        borderRadius: '4px', 
                        cursor: 'pointer'
                    }}
                >
                    ← 返回主页
                </button>
            </div>
            
            <form onSubmit={handleSubmit} style={{ marginBottom: '2rem' }}>
                <div style={{ marginBottom: '1.5rem' }}>
                    <label style={{ 
                        display: 'block', 
                        marginBottom: '0.5rem',
                        fontSize: '1.1rem',
                        fontWeight: 'bold'
                    }}>
                        🏷️ 标题:
                    </label>
                    <input 
                        type="text" 
                        value={title} 
                        onChange={(e) => setTitle(e.target.value)} 
                        style={{ 
                            width: '100%', 
                            padding: '12px', 
                            boxSizing: 'border-box',
                            fontSize: '16px',
                            borderRadius: '4px',
                            border: '1px solid #ddd'
                        }} 
                        required
                        placeholder="请输入知识点标题"
                    />
                </div>
                
                <div style={{ 
                    display: 'flex', 
                    gap: '30px', 
                    marginBottom: '1.5rem',
                    flexWrap: 'wrap'
                }}>
                    <div style={{ 
                        flex: 1, 
                        display: 'flex', 
                        flexDirection: 'column',
                        minWidth: '300px'
                    }}>
                        <label style={{ 
                            display: 'block', 
                            marginBottom: '0.5rem',
                            fontSize: '1.1rem',
                            fontWeight: 'bold'
                        }}>
                            📝 内容 (支持Markdown语法):
                        </label>
                        <textarea
                            value={content}
                            onChange={(e) => setContent(e.target.value)}
                            style={{ 
                                flex: 1, 
                                width: '100%', 
                                height: '500px', 
                                padding: '15px', 
                                boxSizing: 'border-box', 
                                fontFamily: 'monospace',
                                fontSize: '15px',
                                borderRadius: '4px',
                                border: '1px solid #ddd',
                                resize: 'vertical'
                            }}
                            required
                            placeholder="请输入知识点内容，支持Markdown语法..."
                        />
                    </div>
                    
                    <div style={{ 
                        flex: 1, 
                        display: 'flex', 
                        flexDirection: 'column',
                        minWidth: '300px'
                    }}>
                        <label style={{ 
                            display: 'block', 
                            marginBottom: '0.5rem',
                            fontSize: '1.1rem',
                            fontWeight: 'bold'
                        }}>
                            👁️ 实时预览:
                        </label>
                        <div 
                            ref={mermaidContainerRef}
                            style={{ 
                                flex: 1, 
                                height: '500px', 
                                padding: '15px', 
                                boxSizing: 'border-box', 
                                backgroundColor: '#f9f9f9', 
                                border: '1px solid #ddd', 
                                borderRadius: '4px',
                                overflowY: 'auto',
                                lineHeight: '1.6'
                            }}
                        >
                            <ReactMarkdown 
                                remarkPlugins={[remarkGfm, remarkMath]}
                                rehypePlugins={[rehypeKatex]}
                                components={{
                                    code({node, inline, className, children, ...props}) {
                                        const match = /language-(\w+)/.exec(className || '')
                                        if (match && match[1] === 'mermaid') {
                                            return <div className="mermaid" style={{ 
                                                backgroundColor: '#fff', 
                                                padding: '15px', 
                                                borderRadius: '4px',
                                                margin: '15px 0',
                                                border: '1px solid #eee'
                                            }}>
                                                {String(children).replace(/\n$/, '')}
                                            </div>;
                                        }
                                        return <code className={className} {...props}>{children}</code>;
                                    }
                                }}
                            >
                                {content || '请输入内容以查看预览...'}
                            </ReactMarkdown>
                        </div>
                    </div>
                </div>
                
                <div style={{ 
                    display: 'flex', 
                    gap: '30px', 
                    marginBottom: '1.5rem',
                    flexWrap: 'wrap'
                }}>
                    <div style={{ 
                        flex: 1,
                        minWidth: '300px'
                    }}>
                        <label style={{ 
                            display: 'block', 
                            marginBottom: '0.5rem',
                            fontSize: '1.1rem',
                            fontWeight: 'bold'
                        }}>
                            💡 Markdown 语法提示:
                        </label>
                        <div style={{ 
                            height: '250px', 
                            padding: '15px', 
                            boxSizing: 'border-box', 
                            backgroundColor: '#f5f5f5', 
                            overflowY: 'auto', 
                            fontSize: '14px',
                            fontFamily: 'monospace',
                            borderRadius: '4px',
                            border: '1px solid #ddd'
                        }}>
                            <pre style={{ margin: 0 }}>
                                {markdownTips}
                            </pre>
                        </div>
                    </div>
                    
                    <div style={{ 
                        flex: 1,
                        minWidth: '300px',
                        display: 'flex',
                        flexDirection: 'column',
                        justifyContent: 'flex-end'
                    }}>
                        <div style={{ 
                            padding: '20px',
                            backgroundColor: '#e3f2fd',
                            borderRadius: '8px',
                            border: '1px solid #bbdefb'
                        }}>
                            <h3 style={{ 
                                marginTop: 0,
                                color: '#1976D2'
                            }}>
                                📌 使用提示
                            </h3>
                            <ul style={{ 
                                paddingLeft: '20px',
                                marginBottom: '0'
                            }}>
                                <li>使用Markdown语法编写知识点内容</li>
                                <li>支持数学公式和Mermaid图表</li>
                                <li>实时预览功能可即时查看效果</li>
                                <li>标题和内容为必填项</li>
                            </ul>
                        </div>
                    </div>
                </div>
                
                <div style={{ 
                    textAlign: 'center',
                    marginTop: '2rem'
                }}>
                    <button 
                        type="submit" 
                        style={{ 
                            padding: '12px 40px', 
                            backgroundColor: '#007bff', 
                            color: 'white', 
                            border: 'none', 
                            borderRadius: '4px', 
                            cursor: 'pointer',
                            fontSize: '18px',
                            fontWeight: 'bold'
                        }}
                    >
                        {isEditing ? '💾 更新知识点' : '➕ 创建知识点'}
                    </button>
                </div>
            </form>
        </div>
    );
}

export default KnowledgePointFormPage;